/*
 * httprequest.cpp
 *
 *  Created on: Apr 14, 2009
 *      Author: kuncai
 */

#include "httprequest.h"
#include "log.h"
HttpRequest::HttpRequest():HttpMsg(){
	sMethod = "";
	sVersion = "";
	sUri = "";
}
HttpRequest::HttpRequest(string msg):HttpMsg(msg){
	sMethod = "";
	sVersion = "";
	sUri = "";
	Formate(msg);
}
HttpRequest::~HttpRequest(){}
int HttpRequest::SetMethod(string method){
	sMethod = method;
	return 1;
}
string HttpRequest::GetMethod(){
	return sMethod;
}
int HttpRequest::SetVersion(string version){
	sVersion = version;
	return 1;
}
string HttpRequest::GetVersion(){
	return sVersion;
}
int HttpRequest::SetUri(string uri){
	sUri = uri;
	return 1;
}
string HttpRequest::GetUri(){
	return sUri;
}

int HttpRequest::SetParam(string paramName, string paramValue){
	pair<map<string, string>::iterator, bool> Insert_Pair;
	Insert_Pair = mParams.insert(pair<string, string>(paramName, paramValue));
	if(Insert_Pair.second == true)
		return true;
	else
		return false;
}

string HttpRequest::GetParam(string paramName){
	string value="";
	map<string,string>::iterator iter;
	iter = mParams.find(paramName); 
	if(iter != mParams.end()){
		value = iter->second;
	}
	return value;
}
Buffer HttpRequest::ToBuffer(){
	if(sMsg != ""){
		Buffer bMsg;
		bMsg.Append(sMsg.c_str(),sMsg.length());
		return bMsg;
	}
	//request-line
}
void HttpRequest::FormateParams(string uri){
	//url
	SetParam("url",strspilt(&uri, "?"));		
	//params
	string name,value,key_value;
	while(uri != ""){
		Log::Debug("params: %s\n",uri.c_str());
		name = "";
		value = "";
		key_value = "";
		key_value = strspilt(&uri, "&");	
		if(key_value == uri){
			uri = "";
		}
		Log::Debug("key_value: %s\n",key_value.c_str());
		name = strspilt(&key_value, "=");
		value = key_value;
		Log::Debug("value: %s\n",value.c_str());
		if(name != ""){
			SetParam(name,value);
		}	
	}
}

void HttpRequest::Formate(string str){
	//request-line
	SetMethod(strspilt(&str, " "));
	SetUri(strspilt(&str, " "));
	//get params
	FormateParams(GetUri());
	SetVersion(strspilt(&str, "\r\n"));
	//header
	string name,value;
	while(true){
		name = "";
		name = strspilt(&str,":");
		value = "";
		value = strspilt(&str,"\r\n");
		SetHeader(name,value);
		if(str == "\r\n"){
			strspilt(&str,"\r\n");
			break;
		}
	}
	//body
	Buffer bBody;
	bBody.Append(str.c_str(), str.length());		
	SetContent(&bBody);	
}
